package com.zyx.tl.transmittable;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlCallable;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Yaxi.Zhang
 * @since 2022/4/22 09:17
 * <p>reference:</p>
 *   <p>&emsp;&emsp;<a href='https://juejin.cn/post/6844903710183653383'>interceptor 配合Threadlocal全局处理请求基本信息</a></p>
 *   <p>&emsp;&emsp;
 *   <a href='https://blog.didispace.com/Spring-Cloud%E4%B8%ADHystrix-%E7%BA%BF%E7%A8%8B%E9%9A%94%E7%A6%BB%E5%AF%BC%E8%87%B4ThreadLocal%E6%95%B0%E6%8D%AE%E4%B8%A2%E5%A4%B1/'>
 *   Spring-Cloud中Hystrix-线程隔离导致ThreadLocal数据丢失</a></p>
 */
public class TransmittableThreadLocalDemo {
    private static final ThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();
    private static final ExecutorService pool = TtlExecutors.getTtlExecutorService(new ThreadPoolExecutor(3, 3,
            10, TimeUnit.MINUTES, new LinkedBlockingQueue<>()));

    public static void main(String[] args) {
        transmittableThreadLocal.set("父线程设定的值");
        System.out.println(Thread.currentThread().getName() + "====" + transmittableThreadLocal.get());

        for (int i = 0; i < 5; i++) {
            pool.submit(TtlCallable.get(() -> {
                System.out.println(Thread.currentThread().getName() + "------" + transmittableThreadLocal.get());
                transmittableThreadLocal.set("我被修改了");
                return transmittableThreadLocal.get();
            }));
        }

    }
}
